package com.example.mvpdemo.base;

import android.util.Log;

import com.example.mvpdemo.BuildConfig;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * @auth: njb
 * @date: 2022/11/28 21:48
 * @desc:
 */
public class BaseApi {
    public static final int DEFAULT_TIMEOUT = 20000;//10秒

    protected static OkHttpClient.Builder getHttpClient(final String tagName) {

        //设置缓存路径，系统默认缓存路径，并且限制缓存大小500m
        Cache cache = new Cache(new File(App.getContext().getCacheDir(), "HttpCache"), 500);
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder().cache(cache);
        //httpClientBuilder.addNetworkInterceptor(new HeaderInterceptor());
        httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
        httpClientBuilder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
        httpClientBuilder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
        httpClientBuilder.retryOnConnectionFailure(true);

        //根据当前调试状态，是否显示请求日志
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.e(tagName, message);
                }
            });
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClientBuilder.addInterceptor(interceptor);
            httpClientBuilder.addInterceptor(new CustomLoggingInterceptor());
        }
        return httpClientBuilder;
    }

    static class CustomLoggingInterceptor implements Interceptor {

        private String TAG = BaseApi.class.getSimpleName();

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            Log.i(TAG, "当前请求url-->" + request.url());

            return chain.proceed(request);
        }
    }
}
